import { type KeyboardEvent, useState } from 'react'

const RequiredKeys = ['Control', 'Alt', 'Shift']
const KeysMap = {
  Period: '.',
  Comma: ',',
  Slash: '/',
  Semicolon: ';',
  Quote: '\'',
  LeftBracket: '[',
  RightBracket: ']',
  Backslash: '\\',
  Minus: '-',
  Equal: '=',
}

export function useShortcutInputHandler (
  setShortcutKey: (str: string) => void,
): [(e: KeyboardEvent<HTMLInputElement>) => void] {
  const [keys, setKeys] = useState<string[]>([])

  function getKeycode (keycode: string) {
    if (keycode.includes('Arrow')) {
      return keycode
    }

    if (keycode in KeysMap) {
      return KeysMap[keycode]
    }
    return keycode.replace(/Left|Right|Key|Digit/, '')
  }

  function handleKeydown (e: KeyboardEvent<HTMLInputElement>) {
    const clonedKeys = [...keys]
    const code = getKeycode(e.code)
    if (clonedKeys.includes(code)) return

    setKeys([...clonedKeys, code])
    clonedKeys.push(code)

    if (
      clonedKeys.some(k => RequiredKeys.includes(k)) &&
      !RequiredKeys.includes(code)
    ) {
      setShortcutKey(clonedKeys.join(' + '))
      setKeys([])
    }
  }

  return [handleKeydown]
}
